/*
	* --------------------------------------------------------------------------
	*
  * Copyright 2011 Matt West
	*
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
	*
  *   http://www.apache.org/licenses/LICENSE-2.0
	*
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  * --------------------------------------------------------------------------
*/

function setUp() {
	
	refreshIssues();
	
	chrome.extension.onRequest.addListener(
		function(request, sender, sendResponse) {
		  if (request.cmd == "refresh") {
		  	refreshIssues();
		    sendResponse({status: "message received - refreshing issues"});
	    } else if(request.cmd == "badge") {
				updateBadge();
				sendResponse({status: "message received - updating badge"});
			} else {
		    sendResponse({});
	    }
	});
	
}


/*
*
*/
function refreshIssues() {
	
	projectsArray = localStorage['projects'];
	
	if (projectsArray == undefined || projectsArray.length == 0) {
		
	} else {
	
		projects = JSON.parse(localStorage['projects']);
	
		for (var i = 0; i < projects.length; i++) {
		
			updateProjectIssues(i, projects[i][0], (projects.length - 1));
		
		}
	
		updateLastCheckedTime();
	
		// Set the timer to refresh again
		monitorIssues();
	
	}
}


/*
*
*/
function monitorIssues() {
	
	if (localStorage['interval'] == undefined) {
		// TODO: Change this
		localStorage['interval'] = 1; // Set it to default of every minute
	}
	
	var minutes = localStorage['interval']; // Retrieve the interval set by the user
	
	var interval = 1000*60*minutes; // Calculate the interval in milliseconds
	
	// Refresh the issue tracker at the specified interval;
	setTimeout('refreshIssues()', interval);
	
}


/*
*
*/
function updateBadge() {
	var totalIssues = 0;
	
	var projects = JSON.parse(localStorage['projects']);
	
	for (var i = 0; i < projects.length; i++) {
		
		var project = projects[i];
		var total = project[1].length;
		
		totalIssues += total;
	}
	
	if (totalIssues == 0) {
		var badgeText = '';
	} else {
		var badgeText = totalIssues.toString();
	}
	
	chrome.browserAction.setBadgeText({ 'text': badgeText });
}


/*
*
*/
function updateLastCheckedTime() {

	var d = new Date();
	
	localStorage['lastUpdated'] = d;
	
}


/*
*
*/
function updateProjectIssues(position, project, max) {
	
	var req = new XMLHttpRequest();
	var url = "https://code.google.com/feeds/issues/p/" + project + "/issues/full?can=new";
	
	req.open(
				"GET",
				url,
				true);
	
	req.onload = function() {
		var issues = req.responseXML.getElementsByTagName("entry");
		var newIssues = [];
		
    for (var i = 0, issue; issue = issues[i]; i++) {
      var id = issue.getElementsByTagName("link")[1].getAttribute("href");
      var title = issue.getElementsByTagName("title")[0].childNodes[0].nodeValue;
      var author = issue.getElementsByTagName("name")[0].childNodes[0].nodeValue;
      var content = issue.getElementsByTagName("content")[0].childNodes[0].nodeValue;
      var published = issue.getElementsByTagName("published")[0].childNodes[0].nodeValue;
      
      var newIssue = [id, title, author, content, published];
      
      newIssues.push(newIssue);
    }
		
		
		// Get the projects array
		var projects = JSON.parse(localStorage['projects']);
		
		projects[position][1] = newIssues;
		
		localStorage['projects'] = JSON.stringify(projects);
		
		if (position == max) {
			// Update the browser badge
			updateBadge();
		}
		
	};
	
	req.send(null);
}
